<?php

require_once('db.php');

header('Content-type: application/json');
$action = $_REQUEST['type'];
$session = $_COOKIE['session'];
$out = array();

connect_db('junyi', 'admin123', 'bookmark');

if ($action === 'get-bookmark') {
  $id = $_POST['id'];
  $entry = get_bookmark_by_id($id);

  if (!$entry) {
    $out['entry'] = false;
    $out['info'] = 'not found';
  } else {
    $out['entry'] = $entry;
    $out['info'] = 'ok';
  }

  echo json_encode($out);
  return;
}

if (!$session) {
  $out['info'] = 'need login';
  echo json_encode($out);
  return;
}


$user = get_user_by_session($session);
if (!$user) {
  $out['info'] = 'need login';
  echo json_encode($out);
  return;
}

if ($action === 'add-bookmark') {
  $url = mysql_real_escape_string($_POST['url']);
  $text = mysql_real_escape_string($_POST['desc']);
  $title = mysql_real_escape_string($_POST['title']);

  if (bookmark_exists($url)) {
    $out['info'] = 'exist';
  } else {
    if (!add_bookmark($url, $title, $text, $user)) {
      $out['info'] = "add bookmark failed:" . mysql_error();
    } else {
      $out['info'] = 'ok';
    }
  }

} else if ($action === 'remove-bookmark') {
  $url = mysql_real_escape_string($_POST['url']);
  $ret = remove_bookmark($url);
  if (!$ret) {
    $out['info'] = mysql_error();
  } else {
    $out['info'] = "ok";
  }

} else if ($action === 'edit-bookmark-desc') {
  $id = $_POST['id'];
  $desc = $_POST['desc'];
  $ret = update_bookmark_desc($id, $desc);
  if (!$ret) {
    $out['info'] = mysql_error();
  } else {
    $out['info'] = mysql_affected_rows() .  " rows affected";
  }

} else if ($action === 'edit-bookmark-rate') {
  $id = $_POST['id'];
  $value = $_POST['rate'];
  $ret = update_bookmark_rate($id, $value, $user);
  if (!$ret) {
    $out['info'] = mysql_error();
  } else {
    $out['info'] = 'ok';
  }

} else {
  $out['info'] = 'unknown type: $action';
}

echo json_encode($out);
?>